<template>
    <div class="hello" v-scroll="loadMore">
        <ul class="news">
            <li :key="index" class="news__item" v-for="(news, index) in newslist">
                {{index}}-{{news.bookTitle}}
            </li>
        </ul>
        <p v-if="isLoading">loading...</p>
    </div>
</template>

<script>
    import axios from 'axios';
    export default {
        name: 'HelloWorld',
        data() {
            return {
                newslist: [],
                isLoading: false,
            };
        },
        mounted() {
            this.fetch()
                .then((res) => {
                    this.newslist = res.data.d.result;
                });
        },
        directives: {
            scroll: {
                bind: function(el, binding) {
                    el.addEventListener('scroll', () => {
                        const containerHeight = el.clientHeight;
                        const scrollTop = el.scrollTop;
                        const contentHeight = el.scrollHeight;
                        if (scrollTop + containerHeight >= contentHeight) {
                            binding.value();
                        }
                    });
                }
            }
        },
        methods: {
            loadMore() {
                if (this.isLoading) {
                    return;
                }
                this.isLoading = true;
                this.fetch()
                    .then((res) => {
                        const data = res.data.d.result;
                        this.newslist = [...this.newslist, ...data];//数组拼接
                        this.isLoading = false;
                    })
            },
            fetch() {
                return axios.get('https://easy-mock.com/mock/5a8573cd6fc6e91bdeab4b8b/bookstore/api/books#!method=get');
            },
        }
    };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    .hello {
        height: 300px;
        overflow: auto;
    }
    .news {
        border: 1px solid #ccc;
    }
    h1,
    h2 {
        font-weight: normal;
    }
    ul {
        list-style-type: none;
        padding: 0;
    }
    li {
        margin: 0 10px;
    }
    a {
        color: #42b983;
    }
</style>
